package userFileModuleApi

import (
	"KumquatDrivesServices/StorageEngine"
	"KumquatDrivesServices/common/res"
	"io"
	"net/http"

	//"bytes"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	"github.com/sirupsen/logrus"
)

type getPreviewFileRequest struct {
	PreviewId string `uri:"previewId" binding:"required"`
	FileName  string `uri:"fileName" binding:"required"`
}

func (UserFileModuleApi) GetPreviewFile(c *gin.Context) {
	var req getPreviewFileRequest
	if err := c.ShouldBindUri(&req); err != nil {
		logrus.Errorf("Param error: %v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	filePath, err := getPreviewIdOfFileInfo(req.PreviewId)
	if err != nil {
		if errors.Is(err, redis.Nil) {
			res.FailWithCode(res.PARAM_ERR, c)
			return
		}
		logrus.Errorf("Get preview file error: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	file, getFileErr := StorageEngine.Engine.GetFileWithMetadata(filePath, req.FileName)
	if getFileErr != nil {
		logrus.Errorf("Get preview file error: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	fi, _ := file.Stat()
	defer file.Close()
	buffer := make([]byte, 512)
	n, ReadFileErr := file.Read(buffer)
	if ReadFileErr != nil && ReadFileErr != io.EOF {
		logrus.Errorf("Read file error: %v", ReadFileErr)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	contentType := StorageEngine.Engine.GetFileContentType(buffer[:n])
	c.Header("Content-Type", contentType)
	http.ServeContent(c.Writer, c.Request, file.Name(), fi.ModTime(), file)
}
